<?php
namespace ITSociaal\Themes\Lumber\Hooks;

use ITSociaal\Themes\Lumber\{CreateObjectTrait, LumberSite};
use ITSociaal\Themes\Lumber\Timber as Lumber;
use ITSociaal\Themes\Lumber\TimberMenu;
use Twig_Extension_StringLoader;
use Twig_SimpleFilter;

/**
 * Timber-specific hooks
 */
class Timber implements HooksInterface {

	use CreateObjectTrait;

	/** @var \ITSociaal\Themes\Lumber\LumberSite */
	protected $site;

	/**
	 * Adjusts hooks before they're installed
	 *
	 * @param object $actions
	 * @param object $filters
	 *
	 * @return void
	 */
	public function adjustHooks($actions, $filters) {
		if ($this->isTimberActivated()) {
			unset($actions->admin_notices);
			unset($filters->template_include);
		}

		// get_twig is deprecated
		$filters->get_twig->tag = "timber/twig";
	}

	/**
	 * Things to do before any hooks are triggered
	 *
	 * @return void
	 */
	public function setup() {
		if (!$this->isTimberActivated()) {
			return;
		}

		Lumber::$dirname = ["templates", "views"];
	}

	/**
	 * timber_context filter handler
	 *
	 * @param array $context
	 *
	 * @return array
	 */
	public function filterTimberContext($context) {
		$context["menu"] = $this->createObject(TimberMenu::class);
		$context["site"] = $this->getSite();
		$context["theme"] = $context["site"]->theme;

		return $context;
	}

	/**
	 * timber/twig filter handler
	 *
	 * @param \Twig_Environment $twig
	 *
	 * @return \Twig_Environment
	 */
	public function filterGetTwig($twig) {
		$indent = $this->createObject(
			Twig_SimpleFilter::class,
			"indent",
			[$this, "twigIndent"]
		);

		$twig->addFilter($indent);

		$twig->addExtension(
			$this->createObject(Twig_Extension_StringLoader::class)
		);

		if (defined("WP_DEBUG") && constant("WP_DEBUG")) {
			$twig->enableStrictVariables();
		}

		return $twig;
	}

	/**
	 * template_include filter handler
	 *
	 * @return void
	 */
	public function filterTemplateInclude() {
		return get_template_directory() . "/static/no-timber.html";
	}

	/**
	 * admin_notices action handler
	 *
	 * @return void
	 */
	public function onAdminNotices() {
		include get_template_directory() . "/admin-timber-error.php";
	}

	/**
	 * indent twig filter callback
	 *
	 * @param string $string
	 * @param int    $tabs
	 *
	 * @return string
	 */
	public function twigIndent($string, $tabs = 0) {
		$indent = str_repeat("\t", $tabs);

		return preg_replace(
			"/^\\s+$/m",
			"",
			preg_replace("/^/m", $indent, $string)
		);
	}

	/**
	 * Get or create Site instance
	 *
	 * @return \ITSociaal\Themes\Lumber\LumberSite
	 */
	protected function getSite() {
		return $this->site = $this->site ?: $this->createObject(LumberSite::class);
	}

	/**
	 * Check if Timber library plugin is enabled
	 *
	 * @return bool
	 */
	protected function isTimberActivated() {
		return class_exists("Timber", false);
	}

}

/* vi:set ts=4 sw=4 noet: */
